<template>
    <div>


        <a-form class="smart-query-form">
            <a-row class="smart-query-form-row">
                <a-form-item label="角色名称" class="smart-query-form-item">
                    <a-input-search v-model:value="queryParam.roleName" style="width: 200px" placeholder="请输入角色名称">
                        <template #enterButton>
                            <a-button type="primary" @click="xuanzheRoles">选择</a-button>
                        </template>
                    </a-input-search>

                </a-form-item>
                <a-form-item label="应用名称" class="smart-query-form-item">
                    <a-input style="width: 200px" v-model:value="queryParam.gradingName" allowClear
                        placeholder="请输入应用名称" />
                </a-form-item>
                <a-form-item class="smart-query-form-item smart-margin-left10">
                    <a-button-group>
                        <a-button type="primary" @click="onSearch">
                            <template #icon>
                                <ReloadOutlined />
                            </template>
                            查询
                        </a-button>
                        <a-button type="primary" @click="onAdd">
                            <template #icon>
                                <ReloadOutlined />
                            </template>
                            新增
                        </a-button>
                    </a-button-group>

                </a-form-item>
            </a-row>
        </a-form>

        <a-card size="small" :bordered="true">
            <a-table size="small" bordered :loading="tableLoading" rowKey="id" :columns="columns" :data-source="tabData"
                :pagination="false" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                style="height: 450px;overflow-y: auto;">
                <template #bodyCell="{ record, column }">
                    <template v-if="column.dataIndex === 'action'">
                        <div class="smart-table-operate">

                            <a-button danger @click="deleterRecord(record.id)" type="link">删除</a-button>
                        </div>
                    </template>

                </template>
            </a-table>
            <div style="float: right;right: 10px;">
                <a-pagination v-model:current="queryParam.pageNumber" v-model:page-size="queryParam.pageSize"
                    :page-size-options="pageSizeOptions" :total="queryParam.total" show-size-changer
                    @showSizeChange="onShowSizeChange" @change="onSizeChange">

                </a-pagination>
            </div>

        </a-card>
        <a-modal v-model:visible="visible" title="选择" :footer="null">
            <div style="height: 350px;">
                <a-form class="smart-query-form">
                    <a-row class="smart-query-form-row">
                        <a-form-item label="角色名称" class="smart-query-form-item">
                            <a-input style="width: 200px" v-model:value="queryParam2.roleName" allowClear
                                placeholder="请输入角色名称" />
                        </a-form-item>
                        <a-form-item class="smart-query-form-item smart-margin-left10">
                            <a-button-group>
                                <a-button type="primary" @click="onSearch2">
                                    <template #icon>
                                        <ReloadOutlined />
                                    </template>
                                    查询
                                </a-button>
                                <a-button type="primary" @click="onsubmit">

                                    确定
                                </a-button>
                            </a-button-group>

                        </a-form-item>
                    </a-row>
                </a-form>
                <a-table size="small" bordered :loading="tableLoading" rowKey="id" :columns="columns2"
                    :data-source="tabData2" :pagination="false"
                    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange2, type: 'radio' }">
                    <template #bodyCell="{ record, column }">
                        <template v-if="column.dataIndex === 'category'">
                            <div class="smart-table-operate">

                                {{ record.category == 'static' ? '静态' : '动态' }}
                            </div>
                        </template>

                    </template>
                </a-table>
                <div style="float: right;right: 10px;">
                    <a-pagination v-model:current="queryParam2.pageNumber" v-model:page-size="queryParam2.pageSize"
                        :page-size-options="pageSizeOptions" :total="queryParam2.total" show-size-changer
                        @showSizeChange="onShowSizeChange2" @change="onSizeChange2">
                    </a-pagination>
                </div>
            </div>
        </a-modal>


        <a-modal v-model:visible="visible2" title="新增" :footer="null">
            <div style="height: 400px;">
                <a-form class="smart-query-form">
                    <a-row class="smart-query-form-row">
                        <a-form-item label="应用名称" class="smart-query-form-item">
                            <a-input style="width: 200px" v-model:value="queryParam3.gradingName" allowClear
                                placeholder="请输入应用名称" />
                        </a-form-item>
                        <a-form-item class="smart-query-form-item smart-margin-left10">
                            <a-button-group>
                                <a-button type="primary" @click="onSearch3">
                                    <template #icon>
                                        <ReloadOutlined />
                                    </template>
                                    查询
                                </a-button>
                                <a-button type="primary" @click="onsubmit3">

                                    确定
                                </a-button>
                            </a-button-group>

                        </a-form-item>
                    </a-row>
                </a-form>
                <a-table size="small" bordered :loading="tableLoading" rowKey="id" :columns="columns3"
                    :data-source="tabData3" :pagination="false"
                    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange3 }"
                    style="overflow-y: auto;height: 300px;">
                    <template #bodyCell="{ record, column }">
                        <template v-if="column.dataIndex === 'iconBase64'">
                            <div class="smart-table-operate">

                                <img :src="record.iconBase64" alt="" srcset="" style="width: 32px;height: 32px;">
                            </div>
                        </template>

                    </template>
                </a-table>
                <div style="float: right;right: 10px;">
                    <a-pagination v-model:current="queryParam3.pageNumber" v-model:page-size="queryParam3.pageSize"
                        :page-size-options="pageSizeOptions" :total="queryParam3.total" show-size-changer
                        @showSizeChange="onShowSizeChange3" @change="onSizeChange3">
                    </a-pagination>
                </div>
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch, createVNode } from 'vue';
import { rolesAutoApi } from '/src/api/security/rolesAuto/api';
import { gradingApi } from '/src/api/security/authorization/api';
import { Modal, message } from 'ant-design-vue';

import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import _ from 'lodash';
import { SmartLoading } from '/src/components/framework/smart-loading';
import { smartSentry } from '/src/lib/smart-sentry';

const expandedKeys = ref(['1']);

// -----------------------  筛选 ---------------------
const queryParam = ref({
    gradingName: '',
    roleName: '',
    roleId: "",
    pageSize: 10,
    pageNumber: 1,
    total: 0
});
const queryParam3 = ref({
    gradingName: '',
    roleName: '',
    roleId: "",
    pageSize: 5,
    pageNumber: 1,
    total: 0
});
const queryParam2 = ref({
    gradingName: '',
    roleName: '',
    pageSize: 5,
    pageNumber: 1,
    total: 0
});


const onSelectChange2 = (selectedRowKeys, selectedRows) => {
    queryParam.value.roleName = selectedRows[0].roleName;
    queryParam.value.roleId = selectedRows[0].id;
};
const recordList = ref([]) 
const onSelectChange3 = (selectedRowKeys, selectedRows) => {
    recordList.value = selectedRows
}
const visible2 = ref(false)
function onsubmit() {
    init()
    visible.value = false
}


async function onsubmit3() {
    var gradingId=[]
    var gradingName=[]
    for (let i = 0; i < recordList.value.length; i++) {
        gradingId.push(recordList.value[i].id);
        gradingName.push(recordList.value[i].appName);
    }

    let obj={
        roleId:queryParam.value.roleId,
        grading:gradingId.join(","),
        gradingName:gradingName.join(","),
    }
    let res = await rolesAutoApi.addmemberout(obj);
    if(res.code==0){
        message.success("新增成功")
        init()
        visible2.value = false
    }
}

function onAdd() {
    if (!queryParam.value.roleId) {
        message.info("请选择角色名称")
        return
    }
    getmemberOut()
    visible2.value = true
}

async function getmemberOut() {
    let res = await rolesAutoApi.getmemberoutList(queryParam3.value)
    tabData3.value = res.data.rows;
    queryParam3.value.total = res.data.records

}
function onSearch3() {
    getmemberOut()
}


async function handleOk() {
    form.status = form.status ? 1 : 0
    if (disabledCode.value) {
        let res = await socialsproviderApi.updateSocialsProviderById(form);

        if (res.code == 0) {
            message.success('修改成功');

        } else {
            message.error('修改失败');
        }
    } else {
        let res = await socialsproviderApi.addSocialsProvider(form);

        if (res.code == 0) {
            message.success('新建成功');

        } else {
            message.error('新建失败');
        }
    }

    visible.value = false
    init()
}

function xuanzheRoles() {
    getrolesData()
    visible.value = true
}
const tabData2 = ref([])
const tabData3 = ref([])
async function getrolesData() {
    let res = await gradingApi.getrolesData(queryParam2.value);
    if (res.code == 0) {
        tabData2.value = res.data.rows;
        queryParam2.value.total = res.data.records
    }

}

const onShowSizeChange3 = (current, pageSize) => {
    queryParam3.value.pageNumber = current
    queryParam3.value.pageSize = pageSize
    getmemberOut()
};
const onSizeChange3 = (page, pageSize) => {
    queryParam3.value.pageNumber = page
    queryParam3.value.pageSize = pageSize
    getmemberOut()
};

const columns3 = ref([

    {
        title: '角色名称',
        dataIndex: 'roleName',
        key: 'roleName',
    },
    
])

const columns2 = ref([
    {
        title: '角色名称',
        dataIndex: 'roleName',
        key: 'roleName',
    },
    {
        title: '类型',
        dataIndex: 'category',
        key: 'category',
    },
])


// ----------------------- 表单 ---------------------

const formRef = ref();

const disabledCode = ref(false)

const formDefault = {
    id: undefined,
    icon: undefined,
    provider: undefined,
    providerName: undefined,
    clientId: undefined,
    clientSecret: undefined,
    agentId: undefined,
    scanCode: "false",
    display: "false",
    sortIndex: 1,
    status: 0
};

let form = reactive({ ...formDefault });

// 表单规则
const rules = {
    // icon: [{ required: true, message: '请输入图标' }],
    // provider: [{ required: true, message: '请输入提供者' }],
    // providerName: [{ required: true, message: '请输入名称' }],
    // clientId: [{ required: true, message: '请输入凭证' }],
    // clientSecret: [{ required: true, message: '请输入密钥' }],
    // agentId: [{ required: true, message: '请输入agentId' }],
    // scanCode: [{ required: true, message: '请选择扫码登陆' }],
    // sortIndex: [{ required: true, message: '请输入排序' }],
    // status: [{ required: true, message: '请选择状态' }],
};

const visible = ref(false)
const title = ref("")
const onShowSizeChange = (current, pageSize) => {
    queryParam.value.pageNumber = current
    queryParam.value.pageSize = pageSize
    init()
};
const onSizeChange = (page, pageSize) => {
    queryParam.value.pageNumber = page
    queryParam.value.pageSize = pageSize
    init()
};

const onShowSizeChange2 = (current, pageSize) => {
    queryParam2.value.pageNumber = current
    queryParam2.value.pageSize = pageSize
    getrolesData()
};
const onSizeChange2 = (page, pageSize) => {
    queryParam2.value.pageNumber = page
    queryParam2.value.pageSize = pageSize
    getrolesData()
};

function add() {
    form.id = undefined
    form.icon = undefined
    form.provider = undefined
    form.providerName = undefined
    form.clientId = undefined
    form.clientSecret = undefined
    form.agentId = undefined
    form.scanCode = "false"
    form.display = "false"
    form.sortIndex = 1
    form.status = 0
    title.value = "新建"
    visible.value = true
    disabledCode.value = false
}
//

// ----------------------- 部门树的展示 ---------------------
const tableLoading = ref(false);

const tabData = ref([])

const treeData = ref([])

const pageSizeOptions = ref(['10', '20', '30', '40', '50']);
const onSelectChange = (selectedRowKeys) => {
    // state.selectedRowKeys = selectedRowKeys;
};

const columns = ref([
    {
        title: '角色名称',
        dataIndex: 'roleName',
        key: 'roleName',
    },
    {
        title: '名称',
        dataIndex: 'gradingName',
        key: 'gradingName',
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
    },

]);

onMounted(() => {
    init();
});



function buildTree(data) {
    const tree = [];
    const map = {};
    data.forEach((item) => {
        map[item.key] = { ...item, children: [] };
    });
    data.forEach((item) => {
        const { parentKey } = item;
        if (parentKey === '0') {
            tree.push(map[item.key]);
        } else {
            if (map[parentKey]) {
                map[parentKey].children.push(map[item.key]);
            }
        }
    });
    return tree;
}




// 查询部门列表并构建 部门树
async function init() {
    try {
        tableLoading.value = true;
        let res = await rolesAutoApi.getmemberList(queryParam.value);

        if (res.code == 2) {
            tabData.value = res.data.rows;
            queryParam.value.total = res.data.records
        }
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        tableLoading.value = false;
    }
}



// 重置
function resetQuery() {
    queryParam.value.roleName = ""
    queryParam.value.pageSize = 10
    queryParam.value.pageNumber = 1
    queryParam.value.total = 0
    onSearch();
}

// 搜索
function onSearch() {
    init();
}

function onSearch2() {
    getrolesData();
}



// ----------------------- 表单操作：添加部门/修改部门/删除部门/上下移动 ---------------------


// 编辑
function updateRecord(e) {
    getRecordById(e);
    title.value = "编辑"
    visible.value = true
}

async function getRecordById(id) {
    let res = await socialsproviderApi.getSocialsProviderById(id);
    disabledCode.value = true
    if (res.code == 0) {
        form.id = res.data.id
        form.icon = res.data.icon
        form.provider = res.data.provider
        form.providerName = res.data.providerName
        form.clientId = res.data.clientId
        form.clientSecret = res.data.clientSecret
        form.agentId = res.data.agentId
        form.scanCode = res.data.scanCode
        form.display = res.data.display
        form.sortIndex = res.data.sortIndex
        form.status = res.data.status

    }

}

// 删除
function deleterRecord(id) {
    Modal.confirm({
        title: '提醒',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确定要删除吗?',
        okText: '删除',
        okType: 'danger',
        async onOk() {
            SmartLoading.show();
            try {
                await rolesAutoApi.deletememberout(id);
                init();
            } catch (error) {
                smartSentry.captureError(error);
            } finally {
                SmartLoading.hide();
            }
        },
        cancelText: '取消',
        onCancel() { },
    });
}
</script>

<style scoped lang="less"></style>